package com.example.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.crm.entity.Classify;
import com.example.crm.entity.Product;
import com.example.crm.service.ClassifyService;
import com.example.crm.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class ProductController {

    @Resource
    ClassifyService classifyService;

    @Resource
    ProductService productService;

    @GetMapping("/getClassify")
    public ResponseEntity<List> getData() {
        List<Map<String, Object>> list = classifyService.listMaps();
        return ResponseEntity.ok(list);
    }

    @PostMapping("/addClassify")
    public ResponseEntity<String> addClassify(@RequestBody Classify classify) {
        boolean save = classifyService.save(classify);
        if(save){
            return ResponseEntity.ok("Ok");
        }else{
            return ResponseEntity.ok("noOk");
        }
    }

    @PostMapping("/deleteClassify")
    public ResponseEntity<String> deleteClassify(@RequestBody Classify classify) {
        boolean delete = classifyService.removeById(classify.getId());
        QueryWrapper<Classify> wrapper =new QueryWrapper<>();
        wrapper.eq("parent_id",classify.getId());
        boolean deleteChildren = classifyService.remove(wrapper);
        if (delete) {
            return ResponseEntity.ok("Ok");
        } else {
            return ResponseEntity.ok("noOk");
        }
    }

    @GetMapping("/getProducts")
    public ResponseEntity<List<Product>> getProducts() {
        List<Product> list = productService.list();
        return ResponseEntity.ok(list);
    }

    @PostMapping("/addProduct")
    public ResponseEntity<String> addProduct(@RequestBody Product product) {
        boolean save = productService.save(product);
        if(save){
            return ResponseEntity.ok("Ok");
        }else {
            return ResponseEntity.ok("noOk");
        }
    }

    @PostMapping("/deleteProduct")
    public ResponseEntity<String> deleteProduct(@RequestBody Product product) {
        boolean delete = productService.removeById(product.getId());
        if(delete){
            return ResponseEntity.ok("Ok");
        }else {
            return ResponseEntity.ok("noOk");
        }
    }

    @PostMapping("/updateProduct")
    public ResponseEntity<String> updateProduct(@RequestBody Product product) {
        boolean update = productService.updateById(product);
        if(update){
            return ResponseEntity.ok("Ok");
        }else {
            return ResponseEntity.ok("noOk");
        }
    }
}
